import axios from "axios";
import router from "../router/router.js";
import { BASE_URL } from '../config/urlConfig.js';
import messagePost from './message.js'
import { useTokenStore } from '../stores/tokenStore.js'
const forumAxios = axios.create({
    baseURL: BASE_URL
})

forumAxios.interceptors.request.use(config => {
    const { token } = useTokenStore();
    if (token) {
        config.headers.Authorization = token;
    }
    return config;
});


forumAxios.interceptors.response.use(resp => {

    const { code, message, data } = resp.data;
    // console.log(code);
    ;


    if (code === 0) {
        if (message != '') {
            messagePost({
                message: message,
                type: 'success',
            })
        } else {
            messagePost({
                message: "操作成功",
                type: 'success',
            })
        }
        if (data === '')
            return ''
        if (data !== undefined && data !== null) {
            return data;
        }
        return true;
    }
    if (message != '') {
        messagePost({
            message: message,
            type: 'error',
        })
    }
    if (code === 1104 || code === 1301) {
        router.push('/login')
    }
    return false;

}, error => {
    if (error.response && error.response.status === 401) {
        messagePost({
            message: '未授权，请重新登录',
            type: 'error',
        });
        router.push('/');
        return Promise.reject(error);
    }
    messagePost({
        message: '请求失败',
        type: 'error',
    });
    return Promise.reject(error);
})
export default forumAxios